package com.gongpingjialoan.activity.sell;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.tool.WebViewActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.PhotoModel;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.data.SellPrivateCarBean;
import com.gongpingjialoan.network.UploadCallBack;
import com.gongpingjialoan.utility.PhotoUtil;
import com.gongpingjialoan.utility.UploadUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

/**
 * Created by Administrator on 2016/8/16.
 */
public class SellPrivateStepActivity2 extends BaseActivity implements View.OnClickListener {


    private static final int REQUEST_IMG_TAKE = 8;

    private static final int REQUEST_CROP = 7;

    private SellPrivateCarBean mSellPrivateCarBean;

    private File dir;
    //已上传的图片
    private int uploadedCount = 0;
    //上传图片总数
    private int uploadPhotoCount = 0;
    private int index = 0;

    private PopupWindow mPopupWindow;

    private View mGetPicLayout, mTakePicLayout;

    private ImageView mCloseLayoutImg;

    private String mPhotoPath;

    private LinearLayout photoV, zmPhotoV, topview;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        isScrollPage = true;
        action = "sell_pubCarSource_carImage";
        super.onCreate(savedInstanceState);
        mSellPrivateCarBean = SellPrivateCarBean.getInstance();
        setContentView(R.layout.sell_car_step2);
        setTitle("个人卖车");
        dir = new File(this.getExternalCacheDir(), "gpj");
        if (!dir.exists()) dir.mkdirs();
        initView();
        initPhotoView();
        initNoknow();
    }


    private void initNoknow() {
        View view = findViewById(R.id.no_know);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SellPrivateStepActivity2.this, WebViewActivity.class);
                intent.putExtra("url", Const.maiche);
                intent.putExtra("content", "过户6大证件");
                startActivity(intent);
            }
        });

    }


    public void step2(View v) {
        JSONArray jsonArray = null, identifyArray = null;
        try {
            jsonArray = getPhotoPath(photoV);
            if (jsonArray.length() == 0) {
                Toast.makeText(this, "请上传车源图片", Toast.LENGTH_SHORT).show();
                return;
            }
            identifyArray = getPhotoPath(zmPhotoV);
//            if (identifyArray.length() == 0) {
//                Toast.makeText(this, "请上传车辆证明图片", Toast.LENGTH_SHORT).show();
//                return;
//            }
        } catch (JSONException e) {
        }
        mSellPrivateCarBean.images = jsonArray.toString();
        mSellPrivateCarBean.identify_image = identifyArray.toString();
        startActivity(new Intent(this, SellPrivateStepActivity3.class));
    }


    private void initView() {
        photoV = (LinearLayout) findViewById(R.id.photo_layout);
        zmPhotoV = (LinearLayout) findViewById(R.id.zm_layout);
        View view = LayoutInflater.from(this).inflate(R.layout.include_popup, null);
        topview = (LinearLayout) view
                .findViewById(R.id.topview);
        mCloseLayoutImg = (ImageView) view
                .findViewById(R.id.imgView_close_layout);
        mGetPicLayout = view.findViewById(R.id.layout_get_pic);
        mTakePicLayout = view.findViewById(R.id.layout_take_pic);
        mCloseLayoutImg.setOnClickListener(this);
        mGetPicLayout.setOnClickListener(this);
        mTakePicLayout.setOnClickListener(this);
        mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setAnimationStyle(R.style.PopupMenu);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        Intent intent;
        switch (id) {
            // 从图库获取图片
            case R.id.layout_get_pic:
                mPopupWindow.dismiss();
                //记录可上传最大张数
                mPhotoPath = new File(dir, System.currentTimeMillis() + ".jpg")
                        .getAbsolutePath();
                intent = new Intent(this,
                        PhotoSelectorActivity.class);
                intent.putExtra(PhotoSelectorActivity.KEY_MAX,
                        1);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivityForResult(intent, Const.PICK_PHOTO);
                break;
            // 相机拍照
            case R.id.layout_take_pic:
                mPopupWindow.dismiss();
                mPhotoPath = new File(dir, System.currentTimeMillis() + ".jpg")
                        .getAbsolutePath();
                PhotoUtil.getPhotoFromCamera(this, REQUEST_IMG_TAKE, mPhotoPath);
                break;
            // 关闭布局
            case R.id.imgView_close_layout:
                if (mPopupWindow.isShowing()) {
                    mPopupWindow.dismiss();
                }
                break;
        }
    }


    private void initPhotoView() {
        for (int i = 0; i < photoV.getChildCount(); i++) {
            final int child_index = i;
            LinearLayout linearChild = (LinearLayout) photoV.getChildAt(i);
            final FrameLayout child = (FrameLayout) linearChild.getChildAt(0);
            final ImageView imageView = (ImageView) child.getChildAt(0);
            final TextView textView = (TextView) linearChild.getChildAt(1);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    index = child_index;
                    //这里面写弹框
                    topview.setVisibility(View.VISIBLE);
                    mPopupWindow.showAtLocation(child, Gravity.BOTTOM, 0, 0);
                }
            });
            final ImageView deleteI = (ImageView) child.getChildAt(1);
            if (mSellPrivateCarBean.hashImages != null) {
                String uri = mSellPrivateCarBean.hashImages.get(textView.getTag());
                if (!TextUtils.isEmpty(uri)){
                    Glide.with(this).load(uri).placeholder(R.drawable.photo_add).centerCrop().into(imageView);
                    deleteI.setVisibility(View.VISIBLE);
                    imageView.setTag(R.id.tag_imagekey, textView.getTag());
                    imageView.setTag(R.id.tag_imagepath, uri);
                }

            }
            deleteI.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mSellPrivateCarBean.hashImages != null) {
                        if(mSellPrivateCarBean.hashImages.containsKey(textView.getTag())){
                            mSellPrivateCarBean.hashImages.remove(textView.getTag());
                        }
                    }
                    index = child_index;
                    imageView.setImageResource(R.drawable.photo_add);
                    imageView.setScaleType(ImageView.ScaleType.CENTER);
                    deleteI.setVisibility(View.GONE);
                    imageView.setTag(R.id.tag_imagekey, "");
                    imageView.setTag(R.id.tag_imagepath, "");
                }
            });
        }

        for (int i = 0; i < zmPhotoV.getChildCount(); i++) {
            final int child_index = i;
            LinearLayout linearChild = (LinearLayout) zmPhotoV.getChildAt(i);
            final FrameLayout child = (FrameLayout) linearChild.getChildAt(0);
            final ImageView imageView = (ImageView) child.getChildAt(0);
            final TextView textView = (TextView) linearChild.getChildAt(1);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    index = child_index;
                    //这里面写弹框
                    topview.setVisibility(View.GONE);
                    mPopupWindow.showAtLocation(child, Gravity.BOTTOM, 0, 0);
                }
            });
            final ImageView deleteI = (ImageView) child.getChildAt(1);
            if (mSellPrivateCarBean.hashIdentifyImage != null) {
                String uri = mSellPrivateCarBean.hashIdentifyImage.get(textView.getTag());
                if (!TextUtils.isEmpty(uri)){
                    Glide.with(this).load(uri).placeholder(R.drawable.photo_add).centerCrop().into(imageView);
                    deleteI.setVisibility(View.VISIBLE);
                    imageView.setTag(R.id.tag_imagekey, textView.getTag());
                    imageView.setTag(R.id.tag_imagepath, uri);
                }

            }
            deleteI.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mSellPrivateCarBean.hashIdentifyImage != null) {
                      if(mSellPrivateCarBean.hashIdentifyImage.containsKey(textView.getTag())){
                          mSellPrivateCarBean.hashIdentifyImage.remove(textView.getTag());
                      }
                    }
                    index = child_index;
                    imageView.setImageResource(R.drawable.photo_add);
                    imageView.setScaleType(ImageView.ScaleType.CENTER);
                    deleteI.setVisibility(View.GONE);
                    imageView.setTag(R.id.tag_imagekey, "");
                    imageView.setTag(R.id.tag_imagepath, "");
                }
            });
        }
    }


    //绑定单张图片
    private void bindBitmap(int index, String newPhotoPath, LinearLayout viewGroup) {
        Bitmap bitmap = PhotoUtil.getLocalImage(new File(newPhotoPath));
        LinearLayout linearChild = (LinearLayout) viewGroup.getChildAt(index);
        FrameLayout view = (FrameLayout) linearChild.getChildAt(0);
        ImageView imageView = (ImageView) view.getChildAt(0);
        imageView.setImageBitmap(bitmap);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        ImageView deleteI = (ImageView) view.getChildAt(1);
        imageView.setTag(R.id.tag_imagekey, "uploading");
        deleteI.setVisibility(View.VISIBLE);

        uploadImg(newPhotoPath, index);
    }

    private void unBindding(int index) {
        LinearLayout linearChild = (LinearLayout) photoV.getChildAt(index);
        FrameLayout view = (FrameLayout) linearChild.getChildAt(0);
        ImageView imageView = (ImageView) view.getChildAt(0);
        ImageView deleteI = (ImageView) view.getChildAt(1);
        imageView.setImageResource(R.drawable.photo_add);
        imageView.setScaleType(ImageView.ScaleType.CENTER);
        deleteI.setVisibility(View.GONE);
        imageView.setTag(R.id.tag_imagekey, "");
        imageView.setTag(R.id.tag_imagepath, "");

    }


    private void uploadImg(String path, final int index) {

        UploadUtils.uploadImage(path, new UploadCallBack() {
            @Override
            public void success(final String uri) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        uploadedCount = uploadedCount + 1;
                        if (topview.getVisibility() == View.VISIBLE) {
                            setPhotoPath(index, uri, photoV);
                            if (mSellPrivateCarBean.hashImages != null) {
                                mSellPrivateCarBean.hashImages.put(Const.CarTypes[index], uri);
                            }
                        } else {
                            setPhotoPath(index, uri, zmPhotoV);
                            if (mSellPrivateCarBean.hashIdentifyImage != null) {
                                mSellPrivateCarBean.hashIdentifyImage.put(Const.IndTypes[index], uri);
                            }
                        }

                        if (uploadPhotoCount == uploadedCount) {
                            hidenProgressDialog();
                            Toast.makeText(SellPrivateStepActivity2.this, "上传成功", Toast.LENGTH_SHORT).show();
                            uploadedCount = 0;
                        }
                    }
                });
            }

            @Override
            public void failure() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        unBindding(index);
                    }
                });
            }
        }, API.uploadPic , "");
    }


    private void setPhotoPath(int index, String path, LinearLayout viewgroup) {
        LinearLayout linearChild = (LinearLayout) viewgroup.getChildAt(index);
        FrameLayout child = (FrameLayout) linearChild.getChildAt(0);
        ImageView imageView = (ImageView) child.getChildAt(0);
        if (viewgroup == photoV) {
            imageView.setTag(R.id.tag_imagekey, Const.CarTypes[index]);
        } else {
            imageView.setTag(R.id.tag_imagekey, Const.IndTypes[index]);
        }
        imageView.setTag(R.id.tag_imagepath, path);
    }

    private JSONArray getPhotoPath(LinearLayout v) throws JSONException {
        JSONArray jsa = new JSONArray();
        for (int i = 0; i < v.getChildCount(); i++) {
            LinearLayout linearChild = (LinearLayout) v.getChildAt(i);
            final FrameLayout child = (FrameLayout) linearChild.getChildAt(0);
            final ImageView imageView = (ImageView) child.getChildAt(0);
            String key = (String) imageView.getTag(R.id.tag_imagekey);
            if (!TextUtils.isEmpty(key)) {
                if (!key.equals("uploading")) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("name", key);
                    jsonObject.put("url", imageView.getTag(R.id.tag_imagepath));
                    jsa.put(jsonObject);
                }
            }
        }
        return jsa;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            // Bundle bundle = data.getExtras();
            switch (requestCode) {
                case Const.PICK_PHOTO:
                    showProgressDialog("图片上传中...");
                    if (data != null && data.getExtras() != null) {
                        List<PhotoModel> photos = (List<PhotoModel>) data.getExtras().getSerializable("photos");
                        if (photos == null || photos.isEmpty()) {
                            Toast.makeText(this, "没有选择图片!", Toast.LENGTH_SHORT).show();
                            hidenProgressDialog();
                        } else {

                            //只能单张上传
                            uploadPhotoCount = photos.size();
                            for (int i = 0; i < photos.size(); i++) {
                                String newPhotoPath = new File(dir, System.currentTimeMillis() + ".jpg")
                                        .getAbsolutePath();
                                Bitmap btp = PhotoUtil.getLocalImage(new File(photos.get(i).getOriginalPath()));
                                PhotoUtil.saveLocalImageSquare(btp, new File(newPhotoPath));
                                if (topview.getVisibility() == View.VISIBLE) {
                                    bindBitmap(index, newPhotoPath, photoV);
                                } else {
                                    bindBitmap(index, newPhotoPath, zmPhotoV);
                                }

                            }
                        }
                    }

                    break;

                case REQUEST_IMG_TAKE:
                    PhotoUtil.onPhotoFromCamera(this, REQUEST_CROP, mPhotoPath, 3,
                            2, 2000);
                    break;
                case REQUEST_CROP:
                    showProgressDialog("图片上传中...");
                    uploadPhotoCount = 1;
                    if (topview.getVisibility() == View.VISIBLE) {
                        bindBitmap(index, mPhotoPath, photoV);
                    } else {
                        bindBitmap(index, mPhotoPath, zmPhotoV);
                    }
                    break;
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSellPrivateCarBean.images = "";
        mSellPrivateCarBean.identify_image = "";
    }
}
